//
//  UserMineVC.m
//  WoWeiRenRenOC
//
//  Created by 姜孟东 on 2020/3/17.
//  Copyright © 2020 姜孟东. All rights reserved.
//

#import "UserMineVC.h"
#import "UserMineHeadView.h"
#import "UserMineHeadShowCell.h"
#import "UserMineHeadExitCell.h"
#import "UserSetingVC.h"
#import "AboutWeVC.h"
#import "UserMyInfoViewController.h"
#import "UserVIPPromoteVC.h"
#import "UserMerchantsPromoteVC.h"
#import "ApplySalesmanView.h"
#import "CustomActivity.h"
#import "UserShippingAddressVC.h"
#import "UserCommissionVC.h"
#import "UserOrderMainVC.h"
#import "UserAbulkOrderMainVC.h"
#import "LoginVC.h"
#import "ShareView.h"
#import "NewShareView.h"
#import "UserVIPPromoteVC.h"
#import "ReFundOrderListVC.h"
#import "MyPostersShareView.h"


extern UserModel *userModel;
@interface UserMineVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) UserMineHeadView *headView;
@property (strong, nonatomic) UITableView *tableView;

@property (nonatomic,strong) NSArray *titleArrays;
@property (strong, nonatomic)ApplySalesmanView *applyView;

@end

@implementation UserMineVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self setUi];

    
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)setUi {
    
    [self.view addSubview:self.tableView];
    
//    self.titleArrays = @[@{@"name":@"我的信息",@"icon":@"wodexinxi"},
//                         @{@"name":@"会员推广",@"icon":@"huiyuantuiguang"},
//                         @{@"name":@"商家推广",@"icon":@"shangjiatuiguang"},
//                         @{@"name":@"关于我们",@"icon":@"guanyuwomen"},
//                         @{@"name":@"分享APP",@"icon":@"fenxiang"},
//                         @{@"name":@"设置",@"icon":@"shezhi"},];
     
     
    self.titleArrays = @[   @{@"name":@"我的信息",@"icon":@"wodexinxi"},
                            @{@"name":@"我的订单",@"icon":@"wodedingdan"},
                            @{@"name":@"退款/售后",@"icon":@"wodedingdan"},
                            @{@"name":@"我的拼团",@"icon":@"wodetuangou_on"},
                            @{@"name":@"我的收货地址",@"icon":@"wodeshouhuodizhi"},
                            @{@"name":@"我的佣金",@"icon":@"wodeyongjin"},
                            @{@"name":@"会员推广",@"icon":@"huiyuantuiguang"},
                            @{@"name":@"商家推广",@"icon":@"shangjiatuiguang"},
                            @{@"name":@"分享APP",@"icon":@"fenxiang"},
                            @{@"name":@"我的会员码",@"icon":@"huiyuantuiguang"},
                            @{@"name":@"设置",@"icon":@"shezhi"},];
    if (@available(iOS 11.0, *)) {
        self.tableView.estimatedRowHeight = 0;
        self.tableView.estimatedSectionFooterHeight = 0;
        self.tableView.estimatedSectionHeaderHeight= 0;
        self.tableView.contentInsetAdjustmentBehavior= UIScrollViewContentInsetAdjustmentNever;
    }
    self.applyView = [ApplySalesmanView getView];
    self.applyView.frame = CGRectMake(0, 0, KSCREEN_WIDTH , KSCREEN_HEIGHT);
    self.applyView.backgroundColor = [UIColor colorWithWhite:0.2f alpha: 0.5];
    self.applyView.hidden = YES;
    [self.view addSubview:self.applyView];
    

    if ([CommonTTool isJumpLoginVC:NO]) {
        [self uploadUsetInfo];
    }
    
}


- (UITableView *)tableView {
    if (!_tableView) {
        CGRect frame = CGRectMake(0.0f, 0, kScreenW, kScreenH - New_TabbarHeight);
        UITableView *tableView = [[UITableView alloc] initWithFrame:frame style:UITableViewStylePlain];
            // 设置tableView的headView
        tableView.tableHeaderView = self.headView;
        tableView.tableFooterView = [UIView new];
        tableView.separatorStyle = NO;
        tableView.delegate = self;
        tableView.dataSource = self;
        // 设置tableView的sectionHeadHeight为segmentViewHeight
        tableView.showsVerticalScrollIndicator = false;
        [tableView registerNib:[UINib nibWithNibName:@"UserMineHeadShowCell" bundle:nil] forCellReuseIdentifier:@"UserMineHeadShowCell"];
        [tableView registerNib:[UINib nibWithNibName:@"UserMineHeadExitCell" bundle:nil] forCellReuseIdentifier:@"UserMineHeadExitCell"];
        
        
        _tableView = tableView;
        _tableView.backgroundColor  = VCBgcolor;
        
    }
    
    return _tableView;
}

- (UserMineHeadView *)headView {
    
    if (!_headView) {
        _headView = [UserMineHeadView getView];
        _headView.frame = CGRectMake(0, 0, kScreenW, 184);
        [_headView.shenqingBtn addTarget:self action:@selector(applyViewClick) forControlEvents:UIControlEventTouchUpInside];
        
    }
    if (![CommonTTool isJumpLoginVC:NO]) {
        _headView.shenqingBtn.hidden = YES;
        _headView.tuiguangLabel.hidden = YES;
        _headView.nameLabel.hidden = YES;
        _headView.loginBtn.hidden = NO;
        [_headView.loginBtn addTarget:self action:@selector(jumpLoginVC) forControlEvents:UIControlEventTouchUpInside];
    }else {
        _headView.shenqingBtn.hidden = NO;
        _headView.tuiguangLabel.hidden = NO;
        _headView.nameLabel.hidden = NO;
        _headView.loginBtn.hidden = YES;
    }
    
    return _headView;
}

- (void)jumpLoginVC {
    
    LoginVC *vc = [[LoginVC alloc]initWithNibName:@"LoginVC" bundle:nil];
    [[CommonTTool getCurrentVC].navigationController pushViewController:vc animated:YES];
    
}


- (void)applyViewClick {
    
    if ([userModel.sh_state isEqualToString:@"1"]) {
        self.applyView.hidden = NO;
    }
    if ([userModel.sh_state isEqualToString:@"2"]) {
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle: @"" message: @"我们将在7个工作日内完成审核，如未审核通过请直接电话联系我们" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction: [UIAlertAction actionWithTitle:@"审核中" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action){
           [CommonTTool serviceCallPhone];
        }]];
        [[CommonTTool getCurrentVC] presentViewController: alertController animated: YES completion: nil];
    }
    
    if ([userModel.sh_state isEqualToString:@"3"]) {
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle: @"" message: @"您的审核已通过，具体业务请联系我们" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction: [UIAlertAction actionWithTitle: @"取消" style: UIAlertActionStyleCancel handler:nil]];
        [alertController addAction: [UIAlertAction actionWithTitle:@"确定" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action){
           [CommonTTool serviceCallPhone];
        }]];
        [[CommonTTool getCurrentVC] presentViewController: alertController animated: YES completion: nil];
    }
    
    if ([userModel.sh_state isEqualToString:@"4"]) {
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle: @"" message: @"您的审核未通过，请直接电话联系我们" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction: [UIAlertAction actionWithTitle: @"取消" style: UIAlertActionStyleCancel handler:nil]];
        [alertController addAction: [UIAlertAction actionWithTitle:@"确定" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action){
            [CommonTTool serviceCallPhone];
           
        }]];
        [[CommonTTool getCurrentVC] presentViewController: alertController animated: YES completion: nil];
    }
    
}

#pragma mark- UITableViewDelegate, UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        
        return self.titleArrays.count;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        UserMineHeadShowCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UserMineHeadShowCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.nameLabel.text = self.titleArrays[indexPath.row][@"name"];
        
        cell.iconImageView.image = [UIImage imageNamed:self.titleArrays[indexPath.row][@"icon"]];
        tableView.rowHeight = 50;
        
        return cell;
        
    }else {
        
        UserMineHeadExitCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UserMineHeadExitCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        tableView.rowHeight = 50;
        
        
        return cell;
        
    }
    
    
}


#pragma mark - section头部间距
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {

    return 0.0000001;
}


#pragma mark - section头部视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    UIView *view= [[UIView alloc]initWithFrame:CGRectMake( 0, 0, KSCREEN_WIDTH, 0.00001)];
    view.backgroundColor = [UIColor whiteColor];
    return view;
}

#pragma mark - section底部间距
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 0) {
        
        return 10;
    }
    return 0.0001;
}

#pragma mark - section底部视图
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake( 0, 0, KSCREEN_WIDTH, 0)];
    view.backgroundColor = VCBgcolor;
    return view;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (![CommonTTool isJumpLoginVC:YES]) {
           return;
    }

    if (![CommonTTool isVipShow:YES]) {
        
        return;
    }

    if (indexPath.section == 0) {
        
        
        /*
        switch (indexPath.row) {
            case 0:
            {
               UserMyInfoViewController *vc = [[UserMyInfoViewController alloc]init];
               [self.navigationController pushViewController:vc animated:YES];
               
            }
               break;
            case 1:
            {
               UserVIPPromoteVC *vc = [[UserVIPPromoteVC alloc]init];
               [self.navigationController pushViewController:vc animated:YES];
               
            }
               break;
                
            case 2:
            {
               UserMerchantsPromoteVC *vc = [[UserMerchantsPromoteVC alloc]init];
               [self.navigationController pushViewController:vc animated:YES];
               
            }
               break;
            case 3:
            {
               AboutWeVC *vc = [[AboutWeVC alloc]init];
               [self.navigationController pushViewController:vc animated:YES];
               
            }
               break;
            case 4:
            {
                [self share];
               
            }
               break;
            case 5:
            {
                UserSetingVC *vc = [[UserSetingVC alloc]init];
                [self.navigationController pushViewController:vc animated:YES];
                
            }
                break;
                
            default:
                break;
        }
         
        */
        switch (indexPath.row) {
            //我的信息
            case 0:
            {
               UserMyInfoViewController *vc = [[UserMyInfoViewController alloc]init];
               [self.navigationController pushViewController:vc animated:YES];
               
            }
               break;
            //我的订单
            case 1:
            {
              UserOrderMainVC *vc = [[UserOrderMainVC alloc]init];
              [self.navigationController pushViewController:vc animated:YES];
              
            }
              break;
            //退款/售后
            case 2:
            {
              ReFundOrderListVC *vc = [[ReFundOrderListVC alloc]init];
              [self.navigationController pushViewController:vc animated:YES];
              
            }
              break;
            //我的品团
            case 3:
            {
             UserAbulkOrderMainVC *vc = [[UserAbulkOrderMainVC   alloc]init];
             [self.navigationController pushViewController:vc animated:YES];
             
            }
               break;
            //我的收货地址
            case 4:
            {
             UserShippingAddressVC *vc = [[UserShippingAddressVC alloc]init];
             [self.navigationController pushViewController:vc animated:YES];
             
            }
                break;
            //我的佣金
            case 5:
            {
             UserCommissionVC *vc = [[UserCommissionVC alloc]init];
             [self.navigationController pushViewController:vc animated:YES];
             
            }
                break;
            case 6:
            {
               UserVIPPromoteVC *vc = [[UserVIPPromoteVC alloc]init];
               [self.navigationController pushViewController:vc animated:YES];
               
            }
               break;
                
            case 7:
            {
               UserMerchantsPromoteVC *vc = [[UserMerchantsPromoteVC alloc]init];
               [self.navigationController pushViewController:vc animated:YES];
               
            }
               break;
            case 8:
            {
                [self shareTapClick];
               
            }
               break;
            case 9:
            {
                [NewShareView showView];
                
            }
                break;
            case 10:
            {
                UserSetingVC *vc = [[UserSetingVC alloc]init];
                [self.navigationController pushViewController:vc animated:YES];
                
            }
                break;
                
            default:
                break;
        }
          
        
    }else {
        
        
    }
   
    
}

//- (void)share {
//
//    // 1、设置分享的内容，并将内容添加到数组中
//    NSString *shareText = @"点击链接即可下载我为人人APP:";
//    NSURL *shareUrl = [NSURL URLWithString:@"http://api.ofajs.cn/ofaapi/index.html"];
//    NSArray *activityItemsArray = @[shareText,shareUrl];
//
//    // 自定义的CustomActivity，继承自UIActivity
//    CustomActivity *customActivity = [[CustomActivity alloc]initWithTitle:shareText ActivityImage:[UIImage imageNamed:@""] URL:shareUrl ActivityType:@"Custom"];
//    NSArray *activityArray = @[customActivity];
//
//    // 2、初始化控制器，添加分享内容至控制器
//    UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItemsArray applicationActivities:activityArray];
//    activityVC.modalInPopover = YES;
//    // 3、设置回调
//    if ([UIDevice currentDevice].systemVersion.floatValue >= 8.0) {
//        // ios8.0 之后用此方法回调
//        UIActivityViewControllerCompletionWithItemsHandler itemsBlock = ^(UIActivityType __nullable activityType, BOOL completed, NSArray * __nullable returnedItems, NSError * __nullable activityError){
//            NSLog(@"activityType == %@",activityType);
//            if (completed == YES) {
//                NSLog(@"completed");
//            }else{
//                NSLog(@"cancel");
//            }
//        };
//        activityVC.completionWithItemsHandler = itemsBlock;
//    }else{
//        // ios8.0 之前用此方法回调
//        UIActivityViewControllerCompletionHandler handlerBlock = ^(UIActivityType __nullable activityType, BOOL completed){
//            NSLog(@"activityType == %@",activityType);
//            if (completed == YES) {
//                NSLog(@"completed");
//            }else{
//                NSLog(@"cancel");
//            }
//        };
//        activityVC.completionHandler = handlerBlock;
//    }
//    // 4、调用控制器
//    [[CommonTTool getCurrentVC] presentViewController:activityVC animated:YES completion:nil];
//
//}

- (void)uploadUsetInfo {
    
    [NetRequestTool postUrl:@"user/getUserInfo" parameters:@{} success:^(id responseObject) {
            
           NSDictionary *dic = responseObject[@"object"];
           [[NSUserDefaults standardUserDefaults] setObject:[dic deleteNull] forKey:kUserInfo];
           
            userModel = [UserModel mj_objectWithKeyValues:dic];
       } failure:^(NSInteger statusCode) {
           
       } finish:^{
           SVPDismiss
       }];
    
}

#pragma mark - 分享
- (void)shareTapClick {
    
    ShareView *share =  [ShareView showCodeView];
    share.buttonClick = ^(NSInteger tag) {
        switch (tag) {
            case 101:
            {
                [self shareType:0];
            }
                break;
            case 102:
            {
                 [self shareType:1];
            }
                break;
            case 103:
            {
                [self weiboShare];
            }
                break;
            case 104:
            {
                [MyPostersShareView showView];
                 
            }
                break;
            case 105:
            {
                UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];

                pasteboard.string = [self getShareURL];

                SVP(@"链接已复制");
                 
            }
                break;
            default:
                break;
        }
        
    };
    
}

- (void)shareType:(int)scene {
    WXMediaMessage * message = [WXMediaMessage message];
    message.title = SHARE_TITLE;
    message.description = SHARE_DES;
    [message setThumbImage:[UIImage imageNamed:@"logo2"]];
    
    
    WXWebpageObject * webPageObject = [WXWebpageObject object];
    webPageObject.webpageUrl = [self getShareURL];
    message.mediaObject = webPageObject;
    
    
    
    SendMessageToWXReq *req1 = [[SendMessageToWXReq alloc]init];
    req1.bText = NO;
    req1.message = message;
    //设置分享到朋友圈(WXSceneTimeline)、好友回话(WXSceneSession)、收藏(WXSceneFavorite)
    req1.scene = scene;
    [WXApi sendReq:req1 completion:^(BOOL success) {
        
    }];
//    [WXApi sendReq:req1];
}

- (void)weiboShare {
    
    // 微博分享、需要授权
    WBAuthorizeRequest *request = [WBAuthorizeRequest request];
    request.redirectURI = @"https://api.weibo.com/oauth2/default.html";
    request.scope = @"all";
    request.userInfo = @{@"SSO_From": @"SendMessageToWeiboViewController",
                       @"Other_Info_1": [NSNumber numberWithInt:123],
                       @"Other_Info_2": @[@"obj1", @"obj2"],
                       @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};

    WBMessageObject *message = [WBMessageObject message];

    // 链接
    WBWebpageObject *webpage = [WBWebpageObject object];
    webpage.objectID = @"identifier1";
    webpage.title = SHARE_TITLE;
    webpage.description = SHARE_DES;
    webpage.thumbnailData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"logo2" ofType:@"png"]];
    webpage.webpageUrl = [self getShareURL];

    message.mediaObject = webpage;

    WBSendMessageToWeiboRequest *weiboRequest = [WBSendMessageToWeiboRequest requestWithMessage:message
                                                                                     authInfo:request
                                                                                 access_token:nil];
    //    WBSendMessageToWeiboRequest *weiboRequest = [WBSendMessageToWeiboRequest requestWithMessage:message];
    weiboRequest.userInfo = nil;
    BOOL isSuccess =  [WeiboSDK sendRequest:weiboRequest];
    NSLog(@"分享是否成功 %d",isSuccess);
    
}

- (NSString *)getShareURL {
    
    
    NSString *userCode= @"";
    if ([CommonTTool isStrNull:userModel.my_code]) {
        userCode = @"";
    }else {
        userCode = [NSString stringWithFormat:@"?code=%@",userModel.my_code];
    }
    
    return [NSString stringWithFormat:@"%@%@",SHARE_HOME_URL,userCode];
    
}

@end
